package top.twoteam.equipment.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.twoteam.equipment.entity.EquipmentImage;
import top.twoteam.equipment.service.EquipmentImageService;
import top.twoteam.equipment.utils.Result;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("/equipmentimg")
public class EquipmentImageController {

    @Autowired
    EquipmentImageService equipmentImageService;


    /**
     * 存入照片接口
     * @param eqId
     * @param file
     * @return
     */
    @RequestMapping(value = "/insertimg",method = {RequestMethod.POST})
    public Result insertImage(@RequestParam("eqId") int eqId,
                              @RequestParam MultipartFile file){
        //准备数据
        Result<Object> res = new Result<>();
        EquipmentImage equipmentImage = new EquipmentImage();
        //获取源文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀名
        String pictype = originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println(originalFilename);
        System.out.println(pictype);
        //图片处理逻辑
        try {
            InputStream ins = file.getInputStream();
            byte[] buffer=new byte[1024];
            int len=0;
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            while((len=ins.read(buffer))!=-1){
                bos.write(buffer,0,len);
            }
            bos.flush();
            byte data[] = bos.toByteArray();
            equipmentImage.setPicontent(data);
            equipmentImage.setEqid(eqId);
            System.out.println(pictype);
            equipmentImage.setPictype(pictype);
            equipmentImageService.uploadImage(equipmentImage);
            res.setCode(20000);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return res;
    }

    @RequestMapping(value = "/getimgbyeqid",method = {RequestMethod.GET})
    public Result getImgByEqid(@RequestParam("eqId") int eqId){
        Result<Object> listResult = new Result<>();
        List<EquipmentImage> imageByEqid = equipmentImageService.getImageByEqid(eqId);
        listResult.setCode(20000);
        listResult.setData(imageByEqid);
        return listResult;
    }
}
